package com.dmall.algorithm.chapter03;

import java.util.Arrays;

/**
 * 时间复杂度O(n)
 * 空间复杂度O(1)
 */
public class Leetcode283V2 {

    // 定义[i...n-1]都是0  最开始x的值为0 [0...n-1]的值都是0，相当于所有的都是0
    public void moveZeroes(int[] nums) {
        int x = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                swap(nums, x, i);
                x ++;
            }
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public static void main(String[] args) {
        int[] nums = {0, 1, 0, 3, 12};
        Leetcode283V2 leetcode283 = new Leetcode283V2();
        leetcode283.moveZeroes(nums);
        Arrays.stream(nums).forEach(System.out::println);
    }
}
